package com.ithiema.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ithiema.reggie.common.CustomException;
import com.ithiema.reggie.dto.SetmealDto;
import com.ithiema.reggie.entity.Setmeal;
import com.ithiema.reggie.entity.SetmealDish;
import com.ithiema.reggie.mapper.SetmealMapper;
import com.ithiema.reggie.service.SetmealDishService;
import com.ithiema.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * 套餐关联菜品业务层实现类
 *
 * @author wangxiao
 * @since 2022/11/2 20:39
 */@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Override
    /**
     * 删除套餐
     */
    @Transactional
    public void removeWithDish(List<Long> ids) {
        // 1. 查询该id集合中是否有正在售卖的套餐,如果要是有的话 不允许删除
        // 相当于一个校验的操作
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        // 因为id传递的可能是多个id,所以要用in作为查询条件
        queryWrapper.in(Setmeal::getId,ids);
        // 套餐的售卖状态
        // status,套餐售卖状态
        // 1: 启售,0:禁售
        // 查询启售状态的套餐
        queryWrapper.eq(Setmeal::getStatus,1);
        // 只需要查询符合条件的记录的数量
        // select count(*) from setmeal where id in ('','') and status = 1
        int count = this.count(queryWrapper);
        // 如果返回的数量大于0,那就代表传递进来的数据,有正在售卖的套餐
        if (count > 0){
            throw new CustomException("套餐正在售卖中,不允许删除");
        }
        // 删除套餐
        // delete from setmeal where id in ('','')
//        this.removeById(ids);
            this.removeByIds(ids);
        // 删除套餐和菜品关联关系
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId,ids);
        this.setmealDishService.remove(queryWrapper1);
    }

    @Autowired
     private SetmealDishService setmealDishService;
    @Override
//    当操作新增\删除的时候，并且操作的俩张表及以上时，要开启事务
    @Transactional
    public void saveWitDish(SetmealDto setmealDto) {
//    1.保存套餐类
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto,setmeal);
        this.save(setmeal);
//        保存套餐和菜品关系，判断传入的菜品是否有数据
        if (CollectionUtils.isNotEmpty(setmealDto.getSetmealDishes())){
//            有数据的情况下，再做新增操作
            for (SetmealDish item : setmealDto.getSetmealDishes()) {
                item.setSetmealId(setmeal.getId());
            }
        }
//            保存套餐和菜品的关系
        this.setmealDishService.saveBatch(setmealDto.getSetmealDishes());
    }
}
